package com.flyxiaozhu.erp.admin.configurations;

import com.flyxiaozhu.erp.core.libs.AppException;
import com.flyxiaozhu.erp.core.libs.ErrorCode;
import com.flyxiaozhu.erp.core.libs.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * Description:
 *
 * @author johnny.lu
 * @version 1.0
 * @date 2017/12/30 1:06
 * Created with IDEA
 */
@ControllerAdvice
public class WebControllerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(WebControllerAdvice.class);

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public JSONResult handleResourceNotFoundException(ConstraintViolationException e) {
        logger.debug("constraint violation exception", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations) {
            String errorMsg = violation.getMessage();
            strBuilder.append(errorMsg + "\n");
        }
        return new JSONResult(ErrorCode.INVALID_PARAM, strBuilder.toString());
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    protected JSONResult handleBindException(BindException ex) throws IOException {
        JSONResult result = new JSONResult(ex.getBindingResult());

        return result;
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    protected JSONResult handleMissingServletRequestParameter(MissingServletRequestParameterException ex) throws IOException {
        JSONResult result = new JSONResult(ErrorCode.INVALID_PARAM, "Miss parameter " + ex.getParameterName() + ".");
        return result;
    }

    @ExceptionHandler(value = MissingPathVariableException.class)
    @ResponseBody
    protected JSONResult handleMissingPathVariable(MissingPathVariableException ex) throws IOException {
        JSONResult result = new JSONResult(ErrorCode.INVALID_PARAM, "Miss path variable " + ex.getVariableName() + ".");
        return result;
    }

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    @ResponseBody
    protected JSONResult handleDataIntegrityViolationException(DataIntegrityViolationException ex) {
        JSONResult result = new JSONResult(ErrorCode.DUPLICATE_KEY, "数据发生重复");
        return result;
    }

    @ExceptionHandler(value = AppException.class)
    @ResponseBody
    protected JSONResult handleAppException(AppException ex) {
        JSONResult result = new JSONResult(ex.getCode(), ex.getMessage());
        return result;
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseBody
    protected JSONResult handleAppAccessDenied(AccessDeniedException ex) {
        JSONResult result = new JSONResult(ErrorCode.FORBIDDEN, "你没有权限进行此操作");
        return result;
    }
}
